﻿package com.vigmonk.net
{
	import com.vigmonk.events.LoaderEvent;
	
	import flash.display.DisplayObjectContainer;
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.HTTPStatusEvent;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLRequest;
	import flash.utils.Dictionary;		
	/**
	 * 
	 * loaderManager.as
	 * @author VIGMONK
	 * 
	 */
	 
	 /**
	 * 
	 * import com.vigmonk.events.LoaderEvent;
	 * import com.vigmonk.net.LoadManager;
	 * 	
	 * loadManager = new LoadManager();
	 * loadManager.addEventListener(LoaderEvent.LOAD_PROGRESS, progressHandler);
	 * loadManager.addEventListener(LoaderEvent.LOAD_COMPLETE, compHandler);
	 * loadManager.init();
	 * 
	 * function progressHandler(_e:LoaderEvent):void
	 * {
	 * 		trace('idx : ',_e.data.idx);		// 해당 idx 값
	 * 		trace('loaded : ',_e.data.loaded);	// 해당 loaded btyes 값
	 * 		trace('total : ',_e.data.total);	// 해당 total bytes 값
	 * }
	 * function compHandler(_e:LoaderEvent):void
	 * {
	 * 		trace('event : ',_e.data.evt);	// 해당 event
	 * 		trace('idx : ',_e.data.idx);	// 해당 idx 값
	 * }
	 * 
	 * // 일반적으로 이미지 로드 시.
	 * loadManager.load(tarMc,'http://www.vigmonk.com/a.jpg');
	 * 
	 * // idx값이 필요 시.
	 * loadManager.load(tarMc,'http://www.vigmonk.com/a.jpg',1);
	 * loadManager.load(tarMc,'http://www.vigmonk.com/a.jpg','img01');
	 * 
	 * // 이미지 로딩중, 해당 로딩 stop/제거
	 * loadManager.stopLoading(1);
	 * loadManager.stopLoading('img01');
	 * 
	 */
	 
	public class LoadManager extends EventDispatcher
	{
		private var loaderDic:Dictionary;
		private var idxDic:Dictionary;
		
		public function LoadManager():void{}
		
		public function init():void
		{
			loaderDic 	= new Dictionary();
			idxDic 		= new Dictionary();
		}
		
		public function load(_mc:DisplayObjectContainer,_urlStr:String,_loadIdx:Object=null):void
		{
			var loader:Loader = new Loader();
			loader.load(new URLRequest(_urlStr));
			setListener(loader);
			
			idxDic[loader.contentLoaderInfo]	= {mc:_mc,idx:_loadIdx};
			loaderDic[_loadIdx] 				= loader;
		}
		
		/**
		 * 외부에서 idx값으로 로딩 취소, 이벤트 핸들러와 dictionary 제거
		 */
		public function stopLoading(_loadIdx:Object):void
		{
			var loader:Loader = loaderDic[_loadIdx];
			if(loader!=null){
				if(loader.numChildren>0)loader.unload();
				removeListener(loader);
			}
			delete idxDic[loader];
			delete loaderDic[_loadIdx];
		}
		
		/**
		 *  각 이벤트 핸들러 등록 및 제거 
		 */
		private function setListener(_loader:Loader):void
		{
			_loader.contentLoaderInfo.addEventListener(Event.COMPLETE,completeHandler);
			_loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS,progressHandler);
			_loader.contentLoaderInfo.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
            _loader.contentLoaderInfo.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
            _loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);	
		}
		private function removeListener(_loader:Loader):void
		{
			_loader.contentLoaderInfo.removeEventListener(Event.COMPLETE,completeHandler);
			_loader.contentLoaderInfo.removeEventListener(ProgressEvent.PROGRESS,progressHandler);
			_loader.contentLoaderInfo.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
            _loader.contentLoaderInfo.removeEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
            _loader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);	
		}
		
		/**
		 * 완료되면 대상 mc에 로드된 녀석만 addChild
		 * 로더는 지움.
		 */
		private function completeHandler(_e:Event):void
		{
			var loaderInfo:LoaderInfo 	= LoaderInfo(_e.target);
			var curDic:Object			= idxDic[loaderInfo];
			var idx:Object 				= curDic.idx;
			
			curDic.mc.addChild(loaderInfo.content);
			stopLoading(idx);
			dispatchEvent(new LoaderEvent(LoaderEvent.LOAD_COMPLETE,{evt:_e,idx:idx}));
		}
		private function progressHandler(_e:ProgressEvent):void
		{
			var idx:Object = idxDic[_e.target].idx;
			dispatchEvent(new LoaderEvent(LoaderEvent.LOAD_PROGRESS,{idx:idx, loaded:_e.bytesLoaded, total:_e.bytesTotal}));
		}
		private function securityErrorHandler(_e:SecurityErrorEvent):void 
		{
			dispatchEvent(new LoaderEvent(LoaderEvent.SECURITY_ERROR,{evnt:_e}));
        }
        private function httpStatusHandler(_e:HTTPStatusEvent):void 
		{
			dispatchEvent(new LoaderEvent(LoaderEvent.HTTP_STATUS,{evnt:_e}));
        }
        private function ioErrorHandler(_e:IOErrorEvent):void 
		{
			dispatchEvent(new LoaderEvent(LoaderEvent.IO_ERROR,{evnt:_e}));
		}
	}
}